package com.example.aigc_education.integration.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.aigc_education.integration.ZhipuServiceIntegration;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.stereotype.Service;

import java.io.IOException;
@Service
@Slf4j
public class ZhipuServiceIntegrationImpl implements ZhipuServiceIntegration {
    private  final String IMG_API_URL = "https://open.bigmodel.cn/api/paas/v4/images/generations";
    private  final String API_KEY = "4d76789d6b8b4cfe84877493e4f9ceff.zxe9E4e0DwhJqnYc"; // 替换为你的API密钥

    @Override
    public String zhipuGenImg(String prompt, String size) {
            OkHttpClient client = new OkHttpClient();

        MediaType mediaType = MediaType.parse("application/json");
        //请求体里的prompt和size由方法参数传入
        String json = "{\"model\": \"cogview-4\", \"prompt\": \""+prompt+"\", \"size\": \""+size+"\"}";
//        String json = "{\"model\": \"cogview-4\", \"prompt\": \""+prompt+"\", \"size\": \"1024x1024\"}";

        RequestBody body = RequestBody.create(json, mediaType);
        Request request = new Request.Builder()
                .url(IMG_API_URL)
                .post(body)
                .addHeader("Authorization", "Bearer " + API_KEY)
                .addHeader("Content-Type", "application/json")
                .build();

            try {
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    String responseBodyString = response.body().string();
                    //转为ResponseBody类
                    ResponseBody responseBody = JSON.parseObject(responseBodyString, ResponseBody.class);
                    String url = responseBody.getData()[0].getUrl();
                    return url;
                } else {
                    String string = response.body().string();
                    throw new RuntimeException("生成失败，HTTP request failed with status code: " + response.code());
                }
            } catch (IOException e) {
                throw new RuntimeException("生成失败，HTTP request failed with status code: " + e.getMessage());
            }
    }
    @Data
    public static class ResponseBody {
        private int created;
        private Data[] data;


        @lombok.Data
        public static class Data {
            private String url;

            public String getUrl() {
                return url;
           }
        }
    }
}
